// 导入axios
import axios from 'axios';
import {
  Message
} from 'element-ui'
// 进行一些全局配置
// 公共路由(网络请求地址)
axios.defaults.baseURL = '/api';

//在main.js设置全局的请求次数，请求的间隙
axios.defaults.retry = 5;
axios.defaults.retryDelay = 5000;
 
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    var config = err.config;
    // If config does not exist or the retry option is not set, reject
    if(!config || !config.retry){
      Message({
        showClose: true,
        message: '未知错误',
        type: 'error'
      });
      return Promise.reject(err);
    } 
    
    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;
    
    // Check if we've maxed out the total number of retries
    if(config.__retryCount >= config.retry) {
        // Reject with the error
        Message({
          showClose: true,
          message: '请求失败，请查看网络是否连接成功',
          type: 'error'
        });
        return Promise.reject(err);
    }
    
    // Increase the retry count
    config.__retryCount += 1;
    
    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, config.retryDelay || 1);
    });
    
    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
        return axios(config);
    });
});


//检查是否有token
// axios.interceptors.request.use(
//     config => {
//     //config.headers['language'] = getLocalStorage('type').type;
//     if (!config.headers['X-Litemall-Token']) {
//       config.headers['X-Litemall-Token'] = `${window.localStorage.getItem(
//         'Authorization'
//       ) || ''}`;
//     }   
//     return config;
//   },
//   err => Promise.reject(err)
// )
// 封装自己的get/post方法
export default {
  get: function(path = '', data = {}) {
    return new Promise(function(resolve, reject) {
      axios.get(path, {
        params: data
      })
        .then(function(response) {
          resolve(response.data);
        })
        .catch(function(error) {
          reject(error);
        });
    });
  },
  post: function(path = '', data = {}) {
    return new Promise(function(resolve, reject) {
      axios.post(path, data)
        .then(function(response) {
          resolve(response.data);
        })
        .catch(function(error) {
          reject(error);
        });
    });
  }
};